package cn.ad.server.persistence.redis.serializer;

import java.io.IOException;

import cn.ad.server.domain.ad.GuidValueObject;
import com.baidu.bjf.remoting.protobuf.Codec;
import com.baidu.bjf.remoting.protobuf.ProtobufProxy;
import com.google.protobuf.CodedInputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;

public class ProtocbufRedisSerializer implements RedisSerializer<GuidValueObject> {

	static final Logger logger = LoggerFactory.getLogger(ProtocbufRedisSerializer.class);

	@Override
	public byte[] serialize(GuidValueObject t) throws SerializationException {
		if (t == null)
			return null;
		Codec<GuidValueObject> guidCodec = ProtobufProxy.create(GuidValueObject.class);
		byte[] b = null;
		try {
			b = guidCodec.encode(t);
		} catch (IOException e) {
			logger.error("ProtocbufRedisSerializer serialize ERROR - {}", e);
		}
		return b;
	}

	@Override
	public GuidValueObject deserialize(byte[] bytes) throws SerializationException {
		if (bytes == null)
			return null;
		Codec<GuidValueObject> guidCodec = ProtobufProxy.create(GuidValueObject.class);
		CodedInputStream z = CodedInputStream.newInstance(bytes);
		GuidValueObject o = null;
		try {
			o = guidCodec.readFrom(z);
		} catch (IOException e) {
			logger.error("ProtocbufRedisSerializer deserialize ERROR - {}", e);
		}
		return o;
	}

}
